import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class HttpProcessor implements Processor {
	private static final String D_HTML = "f:";
	private static final int COUNT = 1024;
	static List<User> list = new ArrayList<User>();

	public void Handle(Request request, Response response) {
		try {
			if (request.getUrl().endsWith(".do")) {
				Servlet servlet = null;
				if (request.getUrl().endsWith("addUser.do")) {
					System.out.println(request.getUrl());
					servlet = new AddUesrServlet(list);
					servlet.service(request, response);
				} else if (request.getUrl().endsWith("login.do")) {
					servlet = new LoginServlet(list);
					servlet.service(request, response);
				} else if (request.getUrl().endsWith("alert.do")) {
					servlet = new AlertServlet(list);
					servlet.service(request, response);
				} else if (request.getUrl().endsWith("delete.do")) {
					servlet = new DeleteServlet(list);
					servlet.service(request, response);
				}
			} else if(request.getUrl().equals("/")){
				InputStream input = null;
				try {
					File file = new File(D_HTML+"1.html");
					byte[] bytes = new byte[COUNT];
					input = new FileInputStream(file);
					OutputStream outputStream = response.getOutputStream();
					int count = input.read(bytes, 0, COUNT);
					while (count != -1) {
						outputStream.write(bytes, 0, count);
						count = input.read(bytes, 0, COUNT);
					}

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}else{
				InputStream input = null;
				try {
					File file = new File(D_HTML + request.getUrl());
					byte[] bytes = new byte[COUNT];
					input = new FileInputStream(file);
					OutputStream outputStream = response.getOutputStream();
					int count = input.read(bytes, 0, COUNT);
					while (count != -1) {
						outputStream.write(bytes, 0, count);
						count = input.read(bytes, 0, COUNT);
					}

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

}
